package com.xj.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xj.entity.EncryptionHolder;
import com.xj.isv.crypto.PrivateAppCryptoSHA256;
import com.xj.openapi4j.service.*;
import com.xj.server.serviceInterface.TransfersSaleOrderInterface;
import com.xj.util.Constance;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@ResponseBody
@RestController
public class ApiController {
    @Autowired
    RedisTemplate redisTemplate;
      @Autowired
    StockService stockService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    PriceJustService priceJustService;
    @Autowired
    TransfersSaleOrderInterface transfersSaleOrderInterface;
    @Autowired
    CustomerService customerService;

    @GetMapping(value = "/stock")
    public @ResponseBody
    String updatestock(@Param("code") String code, HttpServletRequest request) throws Exception {
        stockService.transInventory(code);
        return "success";
    }

    //销售订单保存或审核
    @PostMapping(value = "/saleorder", consumes = "application/json", produces = "application/json")
    public @ResponseBody   String salerorderAuditEvent(@RequestBody EncryptionHolder holder) throws JsonProcessingException {
        String  eventAppkey="935527b6c19f4df2bcbf90c341dbf944";
       String  eventAppsecret="bf85eb57476f97bb2c0f93011c1b8db95383a11b";
        PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(eventAppkey, eventAppsecret);
        String decrypt = crypto.decryptMsg(holder);
        log.info("decrypt={}", decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        String content = jsonObject.getString("content");
        if (StringUtils.isNotEmpty(content)) {
            BoundSetOperations<String, String> sets = redisTemplate.boundSetOps(Constance.ysSaleorder);
            JSONObject j1 = JSONObject.parseObject(content);
            if(j1!=null&&j1.getJSONArray("PREPARE_DATA")!=null) {
                JSONArray reportData = j1.getJSONArray("PREPARE_DATA");
                for (int i = 0; i < reportData.size(); i++) {
                    JSONObject detail = reportData.getJSONObject(i);
                    String salecode = detail.getString("code");
                    log.info("保存或审核ys销售订单,订单号为:{}", salecode);
                    if(StringUtils.isNotEmpty(salecode)){
                        sets.add(salecode);
                     redisTemplate.opsForSet().remove(Constance.errorOrder,salecode);
                    }
                }
            }

            if(j1.getJSONObject("BILL_INFO")!=null){
                JSONObject billinfo = j1.getJSONObject("BILL_INFO");
                String billCode = billinfo.getString("billCode");
                String code=billinfo.getString("code");
                if(StringUtils.isNotEmpty(billCode)){
                    log.info("新增或变更销售订单,订单号为:{}", billCode);
                    sets.add(billCode);
                   redisTemplate.opsForSet().remove(Constance.errorOrder,billCode);
                }else if(StringUtils.isNotEmpty(code)){
                    log.info("新增或变更销售订单,订单号为:{}", code);
                    sets.add(code);
                    redisTemplate.opsForSet().remove(Constance.errorOrder,code);
                } else {
                    //刚提交订单，无单号
                    billCode=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    sets.add("XXX"+billCode);
                }
            }

            redisTemplate.expire(Constance.errorOrder,60,TimeUnit.DAYS);
            redisTemplate.expire(Constance.ysSaleorder,40,TimeUnit.DAYS);
        }
        return "success";
    }

    //销售订单弃审
    @PostMapping(value = "/cancelAudit", consumes = "application/json", produces = "application/json")
    public @ResponseBody   String salerorderCancelAuditEvent(@RequestBody EncryptionHolder holder) throws JsonProcessingException {
        String  eventAppkey="6800fd73c4e44bfdaa945e83502fe56d";
        String eventAppsecret="63efcacaa82136badd3e63ca84c7612d021c8795";
        PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(eventAppkey, eventAppsecret);
        String decrypt = crypto.decryptMsg(holder);
        log.info("decrypt={}", decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        String content = jsonObject.getString("content");
        if (StringUtils.isNotEmpty(content)) {
            BoundSetOperations<String, String> sets = redisTemplate.boundSetOps(Constance.cancelAuditOrder);
            JSONObject j1 = JSONObject.parseObject(content);
            if(j1.getJSONObject("BILL_INFO")!=null){
                JSONObject billinfo = j1.getJSONObject("BILL_INFO");
                String billCode = billinfo.getString("billCode");
                log.info("预订单取消审核,订单号为:{}", billCode);
                //只处理预订单
                if(StringUtils.isNotEmpty(billCode)&&billCode.startsWith("YDD")){
                    sets.add(billCode);
                    redisTemplate.opsForSet().remove(Constance.errorOrder,billCode);
                }
            }
            redisTemplate.expire(Constance.errorOrder,60,TimeUnit.DAYS);
            redisTemplate.expire(Constance.cancelAuditOrder,40,TimeUnit.DAYS);
        }
        return "success";
    }
     //现销单驳回或删除事件
    @PostMapping(value = "/delorRejectOrder", consumes = "application/json", produces = "application/json")
    public @ResponseBody   String  delorRjectOrderEvent(@RequestBody EncryptionHolder holder) throws JsonProcessingException {
        String  eventAppkey="c9ca133bd024481d9296ecca89c0663b";
        String eventAppsecret="5312ef2fdc6ceb2932633728a7098419e11aeac3";
        PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(eventAppkey, eventAppsecret);
        String decrypt = crypto.decryptMsg(holder);
        log.info("decrypt={}", decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        String content = jsonObject.getString("content");
        if (StringUtils.isNotEmpty(content)) {
            BoundSetOperations<String, String> sets = redisTemplate.boundSetOps(Constance.delOrRejectOrder);
            JSONObject j1 = JSONObject.parseObject(content);
            if(j1.getJSONObject("BILL_INFO")!=null){
                JSONObject billinfo = j1.getJSONObject("BILL_INFO");
                String billCode = billinfo.getString("billCode");
                log.info("驳回或删除销售订单,订单号为:{}", billCode);
              //  if(StringUtils.isNotEmpty(billCode)&&billCode.startsWith("XXD")){
                    sets.add(billCode);
                    redisTemplate.opsForSet().remove(Constance.errorOrder,billCode);
             //   }
            }
            redisTemplate.expire(Constance.errorOrder,60,TimeUnit.DAYS);
            redisTemplate.expire(Constance.delOrRejectOrder,40,TimeUnit.DAYS);
        }
        return "success";
    }


    //发货单审核
    @PostMapping(value = "/dispatch", consumes = "application/json", produces = "application/json")
    public @ResponseBody   String dispatchVouchAuditEvent(@RequestBody EncryptionHolder holder) throws JsonProcessingException {
       String dispatchAppkey="1666c8fafb7f43149f9351c8442c2dda";
       String  dispatchAppsecret="f000ac2969a97d56f650df6cdcc54f9408cc875c";
        PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(dispatchAppkey, dispatchAppsecret);
        String decrypt = crypto.decryptMsg(holder);
        log.info("dispatch decrypt={}", decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        String content = jsonObject.getString("content");
        if (StringUtils.isNotEmpty(content)) {
            JSONObject j1 = JSONObject.parseObject(content);
            JSONObject billinfo = j1.getJSONObject("BILL_INFO");
            String billid=billinfo.getString("billId");
            redisTemplate.opsForSet().add(Constance.ysDispatch,billid);
            redisTemplate.expire(Constance.ysDispatch,24*60*15,TimeUnit.MINUTES);
        }
        return "success";
    }


    //销售出库单保存
    @PostMapping(value = "/saleout", consumes = "application/json", produces = "application/json")
    public @ResponseBody   String saleoutSaveAuditEvent(@RequestBody EncryptionHolder holder) throws JsonProcessingException {
        String dispatchAppkey="75aa8b20d5e2477398a47fd5b2dbca76";
        String  dispatchAppsecret="943e65b5bc0705cb9404889b7933984cb904176b";
        PrivateAppCryptoSHA256 crypto = PrivateAppCryptoSHA256.newCrypto(dispatchAppkey, dispatchAppsecret);
        String decrypt = crypto.decryptMsg(holder);
        log.info("saleout decrypt={}", decrypt);
        JSONObject jsonObject = JSONObject.parseObject(decrypt);
        String content = jsonObject.getString("content");
        if (StringUtils.isNotEmpty(content)) {
            JSONObject j1 = JSONObject.parseObject(content);
            Long  id = j1.getLongValue("id");
            redisTemplate.opsForSet().add(Constance.ysSaleout,id);
            redisTemplate.expire(Constance.ysSaleout,24*60*15,TimeUnit.MINUTES);
        }
        return "success";
    }


    @GetMapping(value = "/inv")
    public @ResponseBody
    String updateInventory(@Param("code") String  code,@Param("day") Integer  day) throws Exception {
        inventoryService.transInventory(day,code);
        return "success";
    }

    @GetMapping(value = "/order")
    public @ResponseBody
    String transorder(@Param("code") String  code) throws Exception {
        transfersSaleOrderInterface.transSaleorder(code);
        return "success";
    }

    @GetMapping(value = "/price")
    public @ResponseBody
    String updatePrice(@Param("code") String  code) throws Exception {
        priceJustService.transPriceJust(code);
        return "success";
    }

    @GetMapping(value = "/customer")
    public @ResponseBody
    String transCustomer(@Param("code") String  code) throws Exception {
     String str =  customerService.transCustomerBycode(code);
        return  str;
    }

}
